package com.zhangxiaofanfan.hotcode.third;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <a href="https://leetcode.cn/problems/merge-k-sorted-lists/description/?envType=study-plan-v2&envId=top-100-liked">合并 K 个升序链表</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-05-29 08:42:05
 */
public class HotCode034 {
    public static void main(String[] args) {
        ListNode index1 = new ListNode(1);
        index1.next = new ListNode(4);
        index1.next.next = new ListNode(5);
        ListNode index2 = new ListNode(2);
        index2.next = new ListNode(4);
        index2.next.next = new ListNode(6);
        ListNode index3 = new ListNode(2);
        index3.next = new ListNode(6);
        ListNode[] lists = new ListNode[]{index1, index2, index3};
        HotCode034 hotCode = new HotCode034();
        hotCode.mergeKLists(lists);
    }

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        ListNode header = new ListNode();
        ListNode index = header;
        while (true) {
            int minIndex = -1;
            for (int i = 0; i < lists.length; i++) {
                if (lists[i] == null) {
                    continue;
                }
                if (minIndex == -1 || lists[i].val < lists[minIndex].val) {
                    minIndex = i;
                }
            }
            if (minIndex == -1) {
                break;
            }
            index.next = lists[minIndex];
            lists[minIndex] = lists[minIndex].next;
            index = index.next;
        }
        return header.next;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
